﻿using System;
using System.Data.SqlClient;
using System.Linq.Expressions;

namespace PropertyExpression.ControllableQuery.TypedReader
{
    public interface IDataReader<T>
    {
        TProperty GetValue<TProperty>(Expression<Func<T, TProperty>> propertyExpression);
    }

    public static class QueryExtensions
    {
        public static IDataReader<T> GetReader<T>(this IQuery<T> it, SqlDataReader reader)
        {
            return new DataReader<T>(reader);
        }

        private class DataReader<T> : IDataReader<T>
        {
            private readonly SqlDataReader sqlDataReader;

            public DataReader(SqlDataReader sqlDataReader)
            {
                this.sqlDataReader = sqlDataReader;
            }

            public TProperty GetValue<TProperty>(Expression<Func<T, TProperty>> propertyExpression)
            {
                return (TProperty)sqlDataReader[((MemberExpression)propertyExpression.Body).Member.Name];
            }
        }
    }
}